package org.rainbowinverted.charging.device.connect.ykc.server.decoder;

import cn.hutool.core.util.HexUtil;
import org.rainbowinverted.charging.device.connect.ykc.server.constants.YkcConstants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 云快充协议解码器
 * @author hehuaiping
 */
@Slf4j
public class YkcProtocolDecoder extends LengthFieldBasedFrameDecoder {
    public YkcProtocolDecoder() {
        super(1024, 1, 1, 2, 0);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        // 帧开始标志
        int frameStartFlag = in.getUnsignedByte(in.readerIndex());
        if (!YkcConstants.YKC_FRAME_START.equals(frameStartFlag)) {
            log.warn("frameStartFlag: {}, readerIndex: {}", String.format("%02x", frameStartFlag), in.readerIndex());
            // 从帧从找到0x68
            byte[] dataPackage = new byte[in.readableBytes()];
            in.getBytes(in.readerIndex(), dataPackage);
            int frameStartFlagIndex = in.indexOf(in.readerIndex(), in.readableBytes(), YkcConstants.YKC_FRAME_START.byteValue());
            log.warn("data package: {}, frameStartFlagIndex: {}", HexUtil.encodeHexStr(dataPackage), frameStartFlagIndex);
            if (frameStartFlagIndex == -1) {
                // 无效报文
                return null;
            }
            // 跳过无效字节
            in.readerIndex(frameStartFlagIndex);
        }
        return super.decode(ctx, in);
    }
}
